import { useEffect, useRef } from 'react'
import * as echarts from 'echarts'
import styles from './index.module.less'

interface HalfCircleProgressProps {
  title?: string
  value?: number
  total?: number
  unit?: string
  color?: string
}

const HalfCircleProgress = ({
  title = '活动',
  value = 80,
  total = 80,
  unit = 'K',
  color = '#1890ff'
}: HalfCircleProgressProps) => {
  const chartRef = useRef<HTMLDivElement>(null)
  const chartInstance = useRef<echarts.ECharts | null>(null)

  useEffect(() => {
    if (!chartRef.current) return

    // 初始化图表
    if (!chartInstance.current) {
      chartInstance.current = echarts.init(chartRef.current)
    }

    const percentage = total > 0 ? Math.round((value / total) * 100) : 0

		const formatValue = (val: number) => {
			if (val >= 1000) {
				return `${(val / 1000).toFixed(0)}${unit}`
			}
			return `${val}${unit}`
		}

    const option: echarts.EChartsOption = {
			title: [
				{
					text: percentage + '%',
					left: 'center',
					top: '20%',
					textStyle: {
						fontSize: 12,
					}
				},
				{
					text: `${formatValue(value)}/${formatValue(total)}`,
					left: 'center',
					top: '39%',
					textStyle: {
						fontSize: 12,
					}
				}
			],
      series: [
        {
          name: '进度',
          type: 'gauge',
          radius: '90%',
          startAngle: 180,
          endAngle: 0,
          min: 0,
          max: 100,
          splitNumber: 10,
          axisLine: {
						roundCap: true,
            lineStyle: {
              width: 5,
              color: [
                [percentage / 100, color],
                [1, '#e6e6e6']
              ],
							
            }
          },
          pointer: {
            show: false
          },
          axisTick: {
            show: false
          },
          splitLine: {
            show: false
          },
          axisLabel: {
            show: false
          },
          detail: {
            show: false
          },
          data: [
            {
              value: percentage,
              name: ''
            }
          ]
        }
      ]
    }

    chartInstance.current.setOption(option)

    // 响应式调整
    const handleResize = () => {
      chartInstance.current?.resize()
    }
    window.addEventListener('resize', handleResize)

    return () => {
      window.removeEventListener('resize', handleResize)
      chartInstance.current?.dispose()
      chartInstance.current = null
    }
  }, [value, total, color])

  return (
    <div className={styles.halfCircleProgress}>
      <div className={styles.title}>{title}</div>
      <div className={styles.chartContainer} ref={chartRef}></div>
    </div>
  )
}

export default HalfCircleProgress

